#include "Main.h"

#define ELEPHANT_SPR_NUM 12

int64 currentTime;
std::vector<TxDrawingElement*> elements;

void initElements()
{
	elements.push_back(NULL);
	Iw2DInit();
	TxSimpleAnimation* el = TxSimpleAnimation::createSimpleAnimation("elephant_stands.xml", 5);
	el->setPosition(CIwFVec2(200, 200));
	elements[0] = (TxDrawingElement*)el;
}

void drawScene()
{
	CIwColour color;
	color.Set(100, 100, 100, 100);
	Iw2DSurfaceClear(color);
	for(std::vector<TxDrawingElement*>::iterator element = elements.begin(); element != elements.end(); element++)
	{
		if ((*element)->getIsVisible())
		{
			(*element)->drawElement();
		}
	}
	Iw2DSurfaceShow();
}

void freeMemory()
{
	TxResourceManager::getResoureceManager()->cleanManager();
	for(std::vector<TxDrawingElement*>::iterator element = elements.begin(); element != elements.end(); element++)
	{
		delete (*element);
	}
}


int framesShowed = 0;

static int32 fps(void *systemData, void *userData)
{
    s3eTimerSetTimer(1000, fps, NULL);
	std::cout << "FPS: " << framesShowed << std::endl;
	framesShowed = 0;
    return 0;
}


int main()
{
	//FPS
	s3eTimerSetTimer(1000, fps, NULL);

	int64 nextFrameTime = currentTime = s3eTimerGetUTC();
	int frameCounter = 0;
	
	initElements();
	g_Input.Init();

	while (!s3eDeviceCheckQuitRequest())
    {
		currentTime = s3eTimerGetUTC();

		s3eKeyboardUpdate();
        if (s3eKeyboardGetState(s3eKeyAbsBSK) & S3E_KEY_STATE_DOWN)    // Back key is used to exit on some platforms
            break;
		g_Input.Update();

		if (g_Input.getTouchCount() != 0)
		{
			CTouch* touch = g_Input.getTouch(0);
			if (touch != NULL)
			{
				int x = touch->x;
				int y = touch->y;

				elements[0]->moveToPoint(CIwFVec2(x, y), 2000);
			}
		}

		if(nextFrameTime < currentTime)
		{
			framesShowed++;
			drawScene();
			nextFrameTime += 17;
			s3eDeviceYield(0);
		}
		else
		{
			s3eDeviceYield(nextFrameTime - currentTime);
		}
		
    }

	freeMemory();

	elements.clear();

	Iw2DTerminate();

	return EXIT_SUCCESS;
}